package com.ymk.task;

import com.ymk.base.cmd.CmdSign;
import com.ymk.base.mybatis.Pagination;
import com.ymk.base.utlis.ParamsBuilder;
import com.ymk.bo.mch.MchBO;
import com.ymk.core.enums.mch.MchStatusEnum;
import com.ymk.mq.MessageSender;
import com.ymk.service.IMchService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service("StatMchYearTask")
public class StatMchYearTask implements Job {

    private final static Logger logger = LoggerFactory.getLogger(StatMchYearTask.class);

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {
            this.statMerchant();
            logger.info("会员每年统计任务执行");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    private void statMerchant() {
        ParamsBuilder paramsBuilder = ParamsBuilder.newBuild()
                .addParam("status", MchStatusEnum.NORMAL)
                .setReturnStruct("{id:''}");
        Pagination page = new Pagination();
        page.setPageSize(200);
        page.setPageIndex(1);
        page.setParams(paramsBuilder.build());
        page.setStart((page.getPageIndex() - 1) * page.getPageSize());
        List<MchBO> mchBOList = this.mchService.listForPage(page);

        this.sendMchYearStat(mchBOList);
        int count = page.getPageTotal();
        int pages = count/ page.getPageSize();
        if (count%page.getPageSize() != 0){
            pages++;
        }
        for (int i = 2; i <= pages; i++) {
            page.setPageIndex(i);
            page.setStart((page.getPageIndex() - 1) * page.getPageSize());
            mchBOList = this.mchService.listForPage(page);
            this.sendMchYearStat(mchBOList);
        }
    }

    private void sendMchYearStat(List<MchBO> mchVOList) {

       // Integer  year = LocalDate.now().minusYears(1L).getYear();
        Integer  year = LocalDate.now().getYear();

        CmdSign sign = new CmdSign();
        mchVOList.forEach(mchBO -> messageSender.sendStatMchYear(mchBO.getId(), year,sign));
    }

    public static void main(String[] args) {
        Integer  year = LocalDate.now().getYear();
        System.out.println(year);
    }

    @Autowired
    private MessageSender messageSender;
    @Autowired
    private IMchService mchService;
}
